
/**
 * Module dependencies.
 */

var express = require('express');

var app = module.exports = express.createServer(),
    redis = require("redis"),
    ws = require('websocket-server'),
    redisclient = redis.createClient();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'your secret here' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

// app.get('/', function(req, res){
//   var mdl = require('./controllers/IndexController.js');
//  var controller = new mdl.controller(req, res);
//   controller.indexAction(req, res);
// });

/*
 setup controllers
*/
require('./lib/BaseController.js').init_routes(app);

if (!module.parent) {
  app.listen(80);
  console.log("Express server listening on port %d", app.address().port);
}

// Handle WebSocket Requests

var server = ws.createServer({
    debug: true
});

server.addListener("connection", function(conn) {
    conn.send("Connection: " + conn.id);
    conn.name = "Gast_" +(Math.floor(Math.random()*10000) + 1);
    
    conn.redisClient = redis.createClient();
    conn.redisClient.psubscribe("test");
        
    conn.redisClient.on("pmessage", function(pattern, channel, message){
      conn.send(message);
      console.log(message);
    });
    
    conn.addListener("message", function(message) {
      
    });
    
    conn.addListener("close", function() {
        console.log("user closed connection");
    });
});
console.log("Websocket server listening on port %d", app.address().port);
  server.addListener("error", function() {
    console.log(Array.prototype.join.call(arguments, ", "));
});


server.addListener("disconnected", function(conn) {
    server.broadcast("<" + conn.id + "> disconnected");
		console.log("user disconnected");
});

server.listen(8080);